// pages/funcs/near.js
const App = getApp()
import Util from '../../../utils/util'
const citySelector = requirePlugin('citySelector')
let plugin = requirePlugin('routePlan');

Component({
  data: {
    init: false,

    type: 'mer',

    code: '', //城市行政区划码
    city: '', // 城市名称
    locs: '', // 当前位置
    name: '',

    lng: 0,
    lat: 0,

    markers: [],

    pois: [],
    poi: {
      name: ''
    },
    polylines: [{
      "points": [
        {"latitude": 24.479510, "longitude": 118.089480}, // 厦门市左侧点坐标
        {"latitude": 24.479513, "longitude": 118.079480}, // 厦门市右侧点坐标
        {"latitude": 24.490515, "longitude": 118.069480}  // 厦门市上方点坐标
      ],
      "color":"#FF0000DD",
      "width": 5,
      "dottedLine": false
    }],
    polygons: [{
      "points": [
        {"latitude": 24.521497, "longitude": 118.121675}, 
        {"latitude": 24.499833, "longitude": 118.089425}, 
        {"latitude": 24.464206, "longitude": 118.160036},
        {"latitude": 24.485382, "longitude": 118.192934} 
      ],
      "strokeColor": "#FF0000DD",
      "fillColor": "#00FF00DD",
      "strokeWidth": 2
    }],
    "circles": [{
      "latitude": 24.453952, // 圆心纬度
      "longitude": 118.080718, // 圆心经度
      "color": "#FF0000DD", // 圆的颜色
      "fillColor": "#00FF00DD", // 圆的填充颜色
      "radius": 1000, // 圆的半径，单位米
      "strokeWidth": 2 // 圆边框的宽度
    }]
  },
  ready() {
    const options = {
      code: "350200",
      city: "厦门市",
      locs: "118.089480,24.479510"
    }
    this.setData({
      init: true,
      code: options.code,
      city: options.city.replace('市', ''),
      locs: options.locs,
      lng: parseFloat(options.locs.split(',')[0]),
      lat: parseFloat(options.locs.split(',')[1])
    })
    this.execLoadMerchant()
  },
  pageLifetimes: {
    show(){
      const selectedCity = citySelector.getCity() // 选择城市后返回城市信息对象，若未选择返回null
      console.log('selectedCity', selectedCity)
      if (selectedCity) {
        let locs = `${selectedCity.location.longitude},${selectedCity.location.latitude}`
        this.setData({
          code: selectedCity.id,
          city: selectedCity.name,
          locs: locs,
          lng: parseFloat(locs.split(',')[0]),
          lat: parseFloat(locs.split(',')[1])
        })
        this.execLoadMerchant()
      }
    },
    hide(){
      // this.onUnload()
    }
  },
  onShow() {
    const selectedCity = citySelector.getCity() // 选择城市后返回城市信息对象，若未选择返回null
    if (selectedCity) {
      let locs = `${selectedCity.location.longitude},${selectedCity.location.latitude}`
      this.setData({
        code: selectedCity.id,
        city: selectedCity.name,
        locs: locs,
        lng: parseFloat(locs.split(',')[0]),
        lat: parseFloat(locs.split(',')[1])
      })
      this.execLoadMerchant()
    }
  },
  onUnload() {
    citySelector.clearCity()
  },

  methods: {
    doSelectCity() {
      const key = App.Global.QmapKey // 使用在腾讯位置服务申请的key
      const referer = App.Global.Title // 调用插件的app的名称
      // const hotCitys = '' // 用户自定义的的热门城市

      wx.navigateTo({
        url: `plugin://citySelector/index?key=${key}&referer=${referer}`,
      })
    },
    doSearch() {
      if (this.data.type == 'mer') {
        this.execLoadMerchant()
      } else {
        this.execLoadGAS()
      }
    },
    doSelectMarker(e) {
      console.log('doSelectMarker', e)
      this.setData({
        poi: this.data.pois[e.markerId]
      })
    },
    execLoadMerchant() {
      this.setData({
        type: 'mer'
      })
      if (this.data.loadingMerchant || this.data.code == '') {
        return
      }
      this.data.loadingMerchant = true
      App.doPost({
        uri: '/app/base/biz/merchant/near',
        body: {
          city: this.data.code,
          locs: this.data.locs,
          name: this.data.name,
          size: 50
        },
        fnSucc: resp => {
          let idx = 0
          let mks = resp.data.items.map(p => {
            return {
              id: idx++,
              longitude: parseFloat(p.locs.split(',')[0]),
              latitude: parseFloat(p.locs.split(',')[1]),
              width: '32px',
              height: '48px',
              label: {
                content: p.name,
                padding: 5,
                borderWidth: 1,
                borderRadius: 2,
                fontSize: '14',
                bgColor: '#fff'
              }
            }
          })
          let p = resp.data.items.length > 0 ? resp.data.items[0] : {}
          mks.push({
            id: 100,
            longitude: 118.089480,
            latitude: 24.480510,
            width: '40px',
            height: '48px',
            iconPath: '/assets/images/car.png',
            // label: {
            //   content: '我的位置',
            //   padding: 5,
            //   borderWidth: 1,
            //   borderRadius: 2,
            //   fontSize: '14',
            //   bgColor: '#fff'
            // },
            callout: {
              content: '奥迪 A6 2019款',
              padding: 5,
              borderWidth: 1,
              borderRadius: 2,
              fontSize: '14',
              bgColor: '#fff',
              display: 'ALWAYS'
            }
            // customCallout: {
            //   anchorY: 0, // Y轴偏移量
            //   anchorX: 0, // X轴偏移量
            //   display: 'ALWAYS', // 'BYCLICK':点击显示; 'ALWAYS':常显
            // }
          })
          this.setData({
            markers: mks,
            pois: resp.data.items,
            poi: p,
            lng: p.locs ? parseFloat(p.locs.split(',')[0]) : this.data.lng,
            lat: p.locs ? parseFloat(p.locs.split(',')[1]) : this.data.lat,
          })
        },
        fnComp: () => {
          this.data.loadingMerchant = false
        }
      })
    },
    execLoadGAS() {
      this.setData({
        type: 'gas'
      })
      if (this.data.loadingMerchant || this.data.code == '') {
        return
      }
      this.data.loadingMerchant = true
      App.doPost({
        uri: '/app/base/biz/merchant/gas/near',
        body: {
          city: this.data.code,
          locs: this.data.locs,
          name: this.data.name,
          size: 50
        },
        fnSucc: resp => {
          let idx = 0
          let mks = resp.data.items.map(p => {
            return {
              id: idx++,
              longitude: parseFloat(p.locs.split(',')[0]),
              latitude: parseFloat(p.locs.split(',')[1]),
              width: '32px',
              height: '48px',
              label: {
                content: p.name,
                padding: 5,
                borderWidth: 1,
                borderRadius: 2,
                fontSize: '14',
                bgColor: '#fff'
              }
            }
          })
          let p = resp.data.items.length > 0 ? resp.data.items[0] : {}
          this.setData({
            markers: mks,
            pois: resp.data.items,
            poi: p,
            lng: p.locs ? parseFloat(p.locs.split(',')[0]) : this.data.lng,
            lat: p.locs ? parseFloat(p.locs.split(',')[1]) : this.data.lat,
          })
        },
        fnComp: () => {
          this.data.loadingMerchant = false
        }
      })
    },
    toNowloc() {
      this.setData({
        lng: parseFloat(this.data.locs.split(',')[0]),
        lat: parseFloat(this.data.locs.split(',')[1])
      })
    },
    toMchCars(e) {
      let poi = e.currentTarget.dataset.poi
      console.log(poi)
      wx.redirectTo({
        url: `/pages/home/mcar?mchid=${poi.id}&clkid=`,
        fail: (res) => {
          console.log(res)
        }
      })
    },
    doNav() {
      if (!this.data.poi.locs) {
        Util.Notify.warn(`该店没有设置具体位置，无法导航`)
        return
      }
      let lat = this.data.poi.locs.split(',')[1]
      let lng = this.data.poi.locs.split(',')[0]
      wx.openLocation({
        latitude: parseFloat(lat),
        longitude: parseFloat(lng),
        name: this.data.poi.name,
        address: this.data.poi.addr,
        scale: 18
      })
    },

    doTel() {
      if (!this.data.poi.tel) {
        Util.Notify.warn(`该店没有设置联系电话，无法拨号`)
        return
      }
      wx.makePhoneCall({
        phoneNumber: this.data.poi.tel
      })
    },
    goToCarLocation() {
      const key = App.Global.QmapKey // 使用在腾讯位置服务申请的key
      const referer = App.Global.Title // 调用插件的app的名称
      let endPoint = JSON.stringify({  //终点
        'name': '北京西站',
        'latitude': 24.480510,
        'longitude': 118.089480
      });
      wx.navigateTo({
        url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint
      });
    },
    doCurrentLocation() {
      wx.getLocation({
        type: 'gcj02',
        success: (res) => {
          let locs = `${res.longitude},${res.latitude}`
          this.setData({
            locs: locs,
            lng: res.longitude,
            lat: res.latitude
          })
          this.execLoadMerchant()
        }
      })
    }
  }
})